/**
 * FormContas.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormContas.java
 *
 * Created on 10/05/2009, 01:04:55
 */

package frames;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import negocio.notas.ContasPagar;
import negocio.pessoas.Investidor;
import negocio.pessoas.Pessoa;
import utils.Auxiliar;
import utils.ErrorMessage;


/**
 *
 * @author jmsandy
 */
public class FormContas extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    DecimalFormat df             = new DecimalFormat("#,##0.00");
    DefaultTableModel dtm        = null;
    private String idObj         = null;
    private String idEmp         = null;
    private ArrayList lstInv     = null;
    private int situacao         = 0;
    private double valorRecebido = 0;
    private JComboBox cbInv      = null;
    private String errorMessage  = "";
    private boolean insert       = false;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constants">
    public static final int K_FORM_CADASTRO  = 1;
    public static final int K_FORM_EXIBICAO  = 2;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Acessores">
    public boolean getInserted(){
        return insert;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormContas */
    public FormContas() {
        initComponents();
    }
    public FormContas(Integer tipo, String idObj, String idEmp, Double val){
        initComponents();
        this.situacao = tipo;
        this.idObj = idObj;
        this.idEmp = idEmp;
        this.valorRecebido = val;
        this.dtm = (DefaultTableModel)tableContas.getModel();
        initializeMyComponents();
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormContas().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbInformado = new javax.swing.JLabel();
        textValorInformado = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableContas = new javax.swing.JTable();
        btnNovo = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        panelBotao = new javax.swing.JPanel();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setTitle("Contas a Pagar");
        setName("formContasPagar"); // NOI18N
        setResizable(false);

        lbInformado.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbInformado.setText("Valor Informado");

        textValorInformado.setBackground(java.awt.Color.white);
        textValorInformado.setEditable(false);
        textValorInformado.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        textValorInformado.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValorInformado.setPreferredSize(new java.awt.Dimension(10, 26));

        tableContas.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        tableContas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Investidor", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableContas);

        btnNovo.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/new.png"))); // NOI18N
        btnNovo.setToolTipText("Novo");
        btnNovo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNovoMouseClicked(evt);
            }
        });

        btnExcluir.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clear.png"))); // NOI18N
        btnExcluir.setToolTipText("Excluir");
        btnExcluir.setEnabled(false);
        btnExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnExcluirMouseClicked(evt);
            }
        });

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnConfirmar.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        btnConfirmar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ok.png"))); // NOI18N
        btnConfirmar.setText("Confirmar");
        btnConfirmar.setEnabled(false);
        btnConfirmar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnConfirmarMouseClicked(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.setEnabled(false);
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addGap(97, 97, 97)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(121, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnConfirmar});

        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotaoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConfirmar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCancelar, btnConfirmar});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 142, Short.MAX_VALUE)
                        .addComponent(lbInformado)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textValorInformado, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnExcluir)
                    .addComponent(btnNovo)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lbInformado)
                        .addComponent(textValorInformado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-508)/2, (screenSize.height-365)/2, 508, 365);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Events">
    // Insere um novo registro
    private void btnNovoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoMouseClicked
        this.tableContas.updateUI();
        dtm.addRow(new Object[]{"", 0.0});
        btnExcluir.setEnabled(true);
    }//GEN-LAST:event_btnNovoMouseClicked

    // Remove um item da tabela
    private void btnExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExcluirMouseClicked
        // Verifica se o botao esta habilitado
        try{
            if(btnExcluir.isEnabled()){
                // Recebe o registro selecionado no grid
                int index = tableContas.getSelectedRow();

                // Caso tenha sido selecionado algum registro o mesmo e removido
                if(index > -1){
                    dtm = (DefaultTableModel)tableContas.getModel();
                    dtm.removeRow(index);
                    tableContas.updateUI();
                }
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnExcluirMouseClicked
    
    // Fecha e retorna ao formulario anterior
    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelarMouseClicked
    // Confirma a insercao das notas
    private void btnConfirmarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnConfirmarMouseClicked
        if(!insertRecords()){
            if(errorMessage.length() > 0) showMessageError(errorMessage);
        }
        else{
            this.setVisible(false);
            insert =  true;
        }
    }//GEN-LAST:event_btnConfirmarMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbInformado;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JTable tableContas;
    private javax.swing.JTextField textValorInformado;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Message em de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Contas a Pagar",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    private void initializeComboInvestidores(){
        // Recupera uma lista investidores para o empreendimento em questao
        Pessoa p = new Pessoa();
        lstInv = new ArrayList();
        lstInv = p.recLstInvEmpreendimento(idEmp);

        cbInv = new JComboBox();
        cbInv.addItem("");
        for(Pessoa pessoa : (ArrayList<Pessoa>) lstInv){
            cbInv.addItem(pessoa.getNome());
        }
    }

    // Inicializa as colunas padroes da tabela
    private void initializeTable(){
        tableContas.getColumnModel().getColumn(0).setPreferredWidth(372);
        tableContas.getColumnModel().getColumn(0).setResizable(false);
        tableContas.getColumnModel().getColumn(1).setPreferredWidth(98);
        tableContas.getColumnModel().getColumn(1).setResizable(false);
        tableContas.getColumnModel().getColumn(1).setCellRenderer(
                                            Auxiliar.getAlign(Auxiliar.RIGHT));
        tableContas.getColumn(tableContas.getColumnName(0)).setCellEditor(
                new DefaultCellEditor(this.cbInv));
        tableContas.getTableHeader().setReorderingAllowed(false);
        tableContas.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableContas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    // Inicializa o estados de todos os botoes
    private void initializeMyComponents(){
        initializeComboInvestidores();
        initializeTable();
        enableFields();
        textValorInformado.setText("R$ " +
                                  df.format(valorRecebido).replace(",", "."));
    }

    // Habilita os botoes para edicao
    private void enableFields(){
        if(this.situacao == K_FORM_CADASTRO){
            btnNovo.setEnabled(true);
            btnConfirmar.setEnabled(true);
            btnCancelar.setEnabled(true);
            tableContas.setEnabled(true);
            insert = false;
        }
        else{
            btnNovo.setEnabled(false);
            btnConfirmar.setEnabled(false);
            btnCancelar.setEnabled(false);
            tableContas.setEnabled(false);
            insert = true;
            showRecords();
        }
    }

    // Insere a lista de contas ao registro
    private boolean insertRecords(){
        boolean inserted = true;
        double valorTotal = 0.0;
        dtm = (DefaultTableModel)tableContas.getModel();
        ArrayList<ContasPagar> lstContas = new ArrayList<ContasPagar>();
        Hashtable<String, Investidor> hsInv =
                                            new Hashtable<String, Investidor>();
        errorMessage = "";

        try{
            for(int i = 0; i < dtm.getRowCount() && inserted; i++){
                String nome = (String)dtm.getValueAt(i, 0);
                int index = getIndexSelected(nome);
                double val = (Double)dtm.getValueAt(i, 1);

                if(index < 0 && nome.equals("")){
                    inserted = false;
                    errorMessage = ErrorMessage.MSG_CONTAS_INV;
                }
                else{
                    Pessoa p = (Pessoa) lstInv.get(index);
                    Investidor inv;
                    if(!hsInv.containsKey(p.getCod_objeto())){
                        inv = new Investidor();
                        inv = inv.recInvestidorPessoa(p.getCod_objeto());
                        hsInv.put(p.getCod_objeto(), inv);
                    }

                    inv = hsInv.get(p.getCod_objeto());

                    if(val > 0){
                        ContasPagar conta = new ContasPagar();
                        conta.setInvestidor(inv.getCod_objeto());
                        conta.setNota(idObj);
                        conta.setValorPago(val);
                        lstContas.add(conta);
                        valorTotal += val;
                    }
                }
            }

            if(inserted){
                if(valorTotal != valorRecebido){
                    errorMessage = ErrorMessage.MSG_CONTAS_VALOR;
                    inserted = false;
                }
                else{

                    if(JOptionPane.showConfirmDialog(this, "Confirma a inserção?",
                        "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                        inserted = (new ContasPagar()).insert(lstContas, idObj);
                    }
                    else inserted = false;
                }
            }
        }
        catch(ArithmeticException ex){
            errorMessage = ErrorMessage.MSG_GERAL_FORMAT;
            inserted = false;
        }
        catch(IOException ex){
            errorMessage = ErrorMessage.MSG_GERAL_BANCO;
            inserted = false;
        }
        return inserted;
    }

    // Exibe os registros relacionados a nota
    private void showRecords(){
        ArrayList<ContasPagar> lstContas =
                                (new ContasPagar()).recLstContasPorNota(idObj);

        dtm = (DefaultTableModel) tableContas.getModel();
        tableContas.updateUI();

        for(ContasPagar conta : lstContas){

            Pessoa p = (new Pessoa()).recPessoaInvestidor(conta.getInvestidor());
            Object[] obj = new Object[]{p.getNome(),
                        df.format(conta.getValorPago()).replace(",", ".")};
            dtm.addRow(obj);
        }
    }

    private int getIndexSelected(String str){
        int index = -1, i = 0;

        for(Pessoa pessoa : (ArrayList<Pessoa>) lstInv){

            if(pessoa.getNome().equals(str)){
                index = i;
                break;
            }
            i++;
        }
        return index;
    }
    //</editor-fold>
}
